package com.hyg.lib_common.loginpart;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.hyg.lib_base.mainUtils.SPUtils;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.ReceiveData;
import com.hyg.lib_common.DataModel.personal.LoginReceiveUserInfo;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.R;
import com.hyg.lib_common.listener.LoginStateListener;
import com.hyg.lib_common.loginpart.modle.OneKeyReceiveData;
import com.mobile.auth.gatewayauth.ActivityResultListener;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.Tencent;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author: Administrator
 * @date: 2021/3/29
 */
public class LoginFasterUtil {
    Activity context;
    PhoneNumberAuthHelper mAlicomAuthHelper;
    LoginStateListener listener;

    public LoginFasterUtil(Activity context) {
        this.context = context;
        initLoginView();
    }


    public void startLoginView(LoginStateListener listener) {
        this.listener = listener;
        if (mAlicomAuthHelper != null) {
            mAlicomAuthHelper.getLoginToken(context, 5000);
            if (listener != null) {
                listener.OnStart(0);
            }
        } else {
            Toast.makeText(context, "打开登陆页失败！请重试", Toast.LENGTH_SHORT).show();
            if (listener != null) {
                listener.OnFail("打开登陆页失败");
            }
        }
    }

    public void startLoginView() {
        if (mAlicomAuthHelper != null) {
            mAlicomAuthHelper.getLoginToken(context, 5000);
            if (listener != null) {
                listener.OnStart(0);
            }
        }
    }


    public void initLoginView() {
        String info;
        String app_id = "1108033225";
        Tencent mTencent;
        TokenResultListener mTokenListener;
        IWXAPI api;

        mTokenListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                Log.i("lgb", "onTokenSuccess: " + s);
                mAlicomAuthHelper.hideLoginLoading();
                parseReceiveData(s);
            }

            @Override
            public void onTokenFailed(String s) {
                Log.i("lgb", "onTokenFailed: " + s);
                mAlicomAuthHelper.hideLoginLoading();
                parseReceiveData(s);
            }
        };
        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(context, mTokenListener);
        mAlicomAuthHelper.setAuthSDKInfo("CS0btwjtL9RmXgaLJ8e5Eho2mhS5FVfVBEABMLSi672mVUUQNBMVNd1HE/tv4y7qGXt2IIyoMOMvNCoVEX3UezJXdqPWbNPpBdgNZTevHuTwvCjwvO2qMNq8I2MOilxars/OiY3PbMQCsRTQtNJ1U6/sjyoKDXhNOPrEAC3IaLczbLxBSGSnswf3O0M0fi6SkWFCDkS3E8ldeyfexJzEvOeII6eMoq1F/EPWGSBeIzpJWOUsMu+I/H9zJ0m/BYhGxzuoYLy/hoP9ST4icPBqmY8GAlzJarNcuTQkyZ2Wt5r6QiGSxtMPJgIi2DJemWCZ");
        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setNavText("")
                .setNavTextSize((int) context.getResources().getDimension(com.hyg.lib_common.R.dimen.title_text_size))
                .setLogBtnHeight(50)
                .setLogBtnText("本机号码一键登录")
                .setLogBtnTextSize(18)
                .setLogBtnMarginLeftAndRight((int) context.getResources().getDimension(com.hyg.lib_common.R.dimen.loginbtn_margin_left))

                .setNavReturnHidden(true)
                .setStatusBarColor(context.getResources().getColor(com.hyg.lib_common.R.color.white))
                .setLightColor(true)
                .setLogoImgPath("logo_512x")
                .setLogoWidth((int) context.getResources().getDimension(com.hyg.lib_common.R.dimen.logo_width))
                .setLogoHeight((int) context.getResources().getDimension(com.hyg.lib_common.R.dimen.logo_width))
                .setLogoOffsetY(12)
                .setSloganHidden(true)
                .setSwitchAccText("账号密码登录")
                .setSwitchAccHidden(true)
                .setLogBtnBackgroundPath("cor_voilet_deep_big")
                .setLogBtnTextColor(Color.WHITE)
                .setLogoHidden(false)
                .setNavColor(0xffffffff)

                .setNumberColor(Color.BLACK)
                .setNumFieldOffsetY((int) context.getResources().getDimension(com.hyg.lib_common.R.dimen.number_margin_top))
                .setNumberSize(28)

                .setPageBackgroundPath("shape_bg")
                .setAppPrivacyOne("《隐私政策与免责声明》", "http://app.tcmhyg.com/med/privacy.html")
                .setAppPrivacyColor(context.getResources().getColor(R.color.musicTextHint), context.getResources().getColor(R.color.mainMusicColor))
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")

                .setWebNavTextColor(context.getResources().getColor(com.hyg.lib_common.R.color.MainThemeColor3))
                .setWebNavTextSize((int) context.getResources().getDimension(com.hyg.lib_common.R.dimen.title_text_size))
                .setWebNavColor(context.getResources().getColor(com.hyg.lib_common.R.color.white))
                .setNavReturnScaleType(ImageView.ScaleType.CENTER_INSIDE)
                .setWebNavReturnImgPath("back_small")
                .setAuthPageActIn("R.anim.fade", "R.anim.hold")
                .setCheckboxHidden(true)
                .create());

        mAlicomAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder().setLayout(com.hyg.lib_common.R.layout.layout_third_login, new AbstractPnsViewDelegate() {
                    @Override
                    public void onViewCreated(View view) {
                        //这⾥返回的View，不建议⽤强引⽤，如果要⽤，请及时释放，否则容易造成 内存泄漏
                        // findViewById(R.id.xxxx).setOnClickListener(new View.OnCli ckListener() {  @Override public void onClick(View v) { //do something  }  });  }  }).build());

                        findViewById(R.id.ln_wechat_login).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Log.i("lgb", "onClick: wechat");
                                SendAuth.Req req = new SendAuth.Req();
                                req.scope = "snsapi_userinfo";
                                req.state = "wechat_sdk_demo_test";
                                BaseApplication.api.sendReq(req);
                                if (listener != null) {
                                    listener.OnStart(1);
                                }

                            }
                        });

                        findViewById(R.id.ln_password_login).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Log.i("lgb", "onClick: ACCOUNT");
                                context.startActivity(new Intent(context, LoginByPasswordActivity.class));
                            }
                        });

                        findViewById(R.id.ln_code_login).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(context, LoginByCodeActivity.class);
                                intent.putExtra("type", "login");
                                context.startActivity(intent);
                            }
                        });
                    }
                }
        )
                .build());
    }


    public void finishView() {
        if (mAlicomAuthHelper != null)
            mAlicomAuthHelper.quitLoginPage();
    }


    public void parseReceiveData(String result) {
        OneKeyReceiveData receiveData = JSONObject.parseObject(result, OneKeyReceiveData.class);
        String code = receiveData.getCode();
        switch (code) {
            case "600000"://获取token成功
                parseOneClickResult(receiveData);
                break;
            case "700000"://点击返回取消登录
            case "700001"://取消登录
                if (listener != null)
                    listener.OnCancel(receiveData.getMsg());
                break;
//            case "600001"://唤起授权⻚成功
            case "600002"://唤起授权⻚失败
            case "600007"://未检测到sim卡⻚失败
            case "600008"://提示⽤户开启移动⽹络后重试
                if (listener != null)
                    listener.OnOpenFail(receiveData.getMsg());
                break;
            case "600011"://获取token失败
            case "600015":
            case "600021":
                if (listener != null)
                    listener.OnFail(receiveData.getMsg() + "，错误码:" + receiveData.getCode());
                break;
        }

    }


    public void parseOneClickResult(OneKeyReceiveData receiveData) {
        CommonHttpUtil.loginByPhone(receiveData.getToken(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (listener != null)
                    listener.OnFail("连接服务器失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ReceiveData data = JSONObject.parseObject(response.body().string(), ReceiveData.class);
                if (data.getCode().equals("200")) {
                    LoginReceiveUserInfo userInfo = JSONObject.parseObject(data.getData(), LoginReceiveUserInfo.class);
                    UserSPUtils.putUserString(context, "phone", userInfo.getUserInfo().getPhone());
                    UserSPUtils.putUserString(context, "token", userInfo.getToken());
                    if (listener != null) {
                        listener.OnSuccess();
                    }
                    finishView();
                } else {
                    if (listener != null)
                        listener.OnFail(data.getMessage());
                }
            }
        });
    }


}
